<template>
  <div>
    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
      <div>
        <h2 style="margin: 0; color: #333">项目管理</h2>
        <p style="margin: 5px 0 0 0; color: #666">管理团队项目，跟踪项目进度</p>
      </div>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>
        新建项目
      </el-button>
    </div>

    <!-- 项目筛选 -->
    <div style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1)">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.name"
            placeholder="搜索项目名称"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="项目状态" clearable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已暂停" value="已暂停" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.priority" placeholder="优先级" clearable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 项目列表 -->
    <div style="background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1)">
      <el-table :data="projectList" style="width: 100%" v-loading="loading">
        <el-table-column prop="projectName" label="项目名称" min-width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <div :style="{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: getStatusColor(row.projectStatus), marginRight: '8px' }"></div>
              <div>
                <div style="font-weight: 500; color: #333">{{ row.projectName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="projectDescription" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="projectStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.projectStatus)">{{ getStatusText(row.projectStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="projectPriority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.projectPriority)">{{ getPriorityText(row.projectPriority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="projectLeader" label="项目负责人" width="120">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-avatar :size="24" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="margin-right: 8px" />
              <span>{{ row.projectLeader }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="memberCount" label="成员数" width="80" align="center">
          <template #default="{ row }">
            {{ row.projectMembers ? row.projectMembers.split(',').filter(m => m).length : 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-progress :percentage="row.progress" :stroke-width="6" style="flex: 1" :format="(percentage) => percentage.toFixed(1) + '%'" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="120">
          <template #default="{ row }">
            <span style="font-size: 12px; color: #666">{{ formatDate(row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="120">
          <template #default="{ row }">
            <span style="font-size: 12px; color: #666">{{ formatDate(row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewProject(row)">查看</el-button>
            <template v-if="currentUser === row.projectLeader">
              <el-button type="primary" link @click="editProject(row)">编辑</el-button>
              <el-button type="danger" link @click="deleteProject(row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="padding: 20px; text-align: center">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建项目弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新建项目"
      width="600px"
      :before-close="closeCreateDialog"
    >
      <el-form :model="createProjectForm" :rules="createProjectRules" ref="createProjectFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="createProjectForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="projectDescription">
          <el-input
            v-model="createProjectForm.projectDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeader">
          <el-input
            v-model="createProjectForm.projectLeader"
            placeholder="当前用户"
            readonly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="小组成员" prop="projectMembers">
          <el-select
            v-model="createProjectForm.projectMembers"
            placeholder="小组成员"
            multiple
            collapse-tags
            :loading="createMemberLoading"
            style="width: 100%"
          >
            <template v-if="createMemberList.length === 0 && !createMemberLoading">
              <el-option disabled value="">暂无小组成员</el-option>
            </template>
            <el-option
              v-for="user in createMemberList"
              :key="user.id"
              :label="`${user.username} (${user.phone || '无手机号'})`"
              :value="user.username"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            显示的是您作为负责人的小组成员
          </div>
        </el-form-item>
        <el-form-item label="优先级" prop="projectPriority">
          <el-select v-model="createProjectForm.projectPriority" placeholder="请选择优先级">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="createProjectForm.startTime"
            type="date"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="createProjectForm.endTime"
            type="date"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeCreateDialog">取消</el-button>
        <el-button type="primary" @click="saveCreateProject" :loading="savingCreate">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑项目弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑项目"
      width="600px"
      :before-close="closeEditDialog"
    >
      <el-form :model="editProjectForm" :rules="editProjectRules" ref="editProjectFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="editProjectForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="projectDescription">
          <el-input
            v-model="editProjectForm.projectDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeader">
          <el-select v-model="editProjectForm.projectLeader" placeholder="请选择项目负责人" disabled>
            <el-option
              v-for="leader in leaderList"
              :key="leader.id"
              :label="leader.username"
              :value="leader.username"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            项目负责人不可修改
          </div>
        </el-form-item>
        <el-form-item label="小组成员" prop="projectMembers">
          <el-select
            v-model="editProjectForm.projectMembers"
            placeholder="请选择小组成员"
            multiple
            collapse-tags
            :loading="editMemberLoading"
            style="width: 100%"
          >
            <template v-if="editMemberList.length === 0 && !editMemberLoading">
              <el-option disabled value="">无匹配数据</el-option>
            </template>
            <el-option
              v-for="member in editMemberList"
              :key="member.id"
              :label="`${member.username} (${member.phone})`"
              :value="member.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="projectPriority">
          <el-select v-model="editProjectForm.projectPriority" placeholder="请选择优先级">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="editProjectForm.startTime"
            type="date"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="editProjectForm.endTime"
            type="date"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="saveEditProject" :loading="savingEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'
import request from '@/utils/request';
import { Plus, Search, ArrowDown } from '@element-plus/icons-vue'

// 安全关闭新建项目对话框
const closeCreateDialog = () => {
  // 先清空表单数据，避免在关闭动画过程中出现引用错误
  Object.assign(createProjectForm, {
    projectName: '',
    projectDescription: '',
    projectLeader: currentUser.value,
    projectPriority: '中',
    startTime: '',
    endTime: '',
    projectMembers: []
  });
  // 关闭对话框
  showCreateDialog.value = false;
};

// 打开新建项目弹窗
const openCreateDialog = () => {
  // 重置表单
  resetCreateForm();
  // 设置当前用户为项目负责人
  createProjectForm.projectLeader = currentUser.value;
  // 加载当前用户作为leader的小组成员列表，但不自动添加
  loadMembersByLeader(currentUser.value);
  showCreateDialog.value = true;
};

// 响应式数据
const loading = ref(false)
const savingCreate = ref(false)
const savingEdit = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const currentProjectId = ref(null)
const createProjectFormRef = ref()
const editProjectFormRef = ref()
const createMemberLoading = ref(false)
const editMemberLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  priority: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 当前用户信息
const currentUser = ref('')

// 新建项目表单
const createProjectForm = reactive({
  projectName: '',
  projectDescription: '',
  projectLeader: '',
  projectPriority: '中',
  startTime: '',
  endTime: '',
  projectMembers: []
})

// 编辑项目表单
const editProjectForm = reactive({
  projectName: '',
  projectDescription: '',
  projectLeader: '',
  projectPriority: '中',
  startTime: '',
  endTime: '',
  projectMembers: []
})

// 新建项目表单验证规则
const createProjectRules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectDescription: [{ required: true, message: '请输入项目描述', trigger: 'blur' }],
  projectLeader: [{ required: true, message: '请选择项目负责人', trigger: 'change' }],
  projectPriority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  projectMembers: [
      { required: true, message: '请选择小组成员', trigger: 'change' }
    ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
    { type: 'date', message: '开始时间格式不正确', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
    { type: 'date', message: '结束时间格式不正确', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (createProjectForm.startTime && value) {
          if (new Date(value) < new Date(createProjectForm.startTime)) {
            callback(new Error('结束时间不能早于开始时间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

// 编辑项目表单验证规则
const editProjectRules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectDescription: [{ required: true, message: '请输入项目描述', trigger: 'blur' }],
  projectLeader: [{ required: true, message: '请选择项目负责人', trigger: 'change' }],
  projectPriority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  projectMembers: [
      { required: true, message: '请选择小组成员', trigger: 'change' }
    ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
    { type: 'date', message: '开始时间格式不正确', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
    { type: 'date', message: '结束时间格式不正确', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (editProjectForm.startTime && value) {
          if (new Date(value) < new Date(editProjectForm.startTime)) {
            callback(new Error('结束时间不能早于开始时间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

// 项目列表
const projectList = ref([])
// 负责人列表
const leaderList = ref([])
// 新建项目成员列表
const createMemberList = ref([])
// 编辑项目成员列表
const editMemberList = ref([])

// 获取当前用户信息
const getCurrentUserInfo = () => {
  try {
    const systemUser = JSON.parse(localStorage.getItem('system-user') || '{}');
    return systemUser.username || localStorage.getItem('username') || '';
  } catch (error) {
    console.error('解析用户信息失败:', error);
    return localStorage.getItem('username') || '';
  }
};

// 防抖函数
const debounce = (fn, delay = 300) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 加载负责人列表
const loadLeaders = async () => {
  try {
    const response = await request.get('/api/leaders');
    if (response.code === '200') {
      leaderList.value = response.data || [];
    } else {
      ElMessage.error('获取负责人列表失败: ' + response.msg);
    }
  } catch (error) {
    ElMessage.error('获取负责人列表失败');
    console.error('获取负责人列表失败:', error);
  }
}

// 搜索所有用户（用于新建项目）
const searchAllUsers = debounce(async (keyword) => {
  if (!keyword) {
    createMemberList.value = [];
    return;
  }
  createMemberLoading.value = true;
  try {
    const response = await request.get('/api/users/search', {
      params: { username: keyword, phone: keyword }
    });
    if (response.code === '200') {
      // 过滤掉当前负责人（仅当负责人已设置）
createMemberList.value = (response.data || []).filter(user =>
  !createProjectForm.projectLeader || user.username !== createProjectForm.projectLeader
);
    } else {
      ElMessage.error('搜索用户失败: ' + response.msg);
    }
  } catch (error) {
    ElMessage.error('搜索用户失败');
    console.error('搜索用户失败:', error);
  } finally {
    createMemberLoading.value = false;
  }
}, 300);

// 加载编辑项目的小组成员
const loadEditMembers = async (leader) => {
  if (!leader) {
    editMemberList.value = [];
    return;
  }
  editMemberLoading.value = true;
  try {
    const response = await request.get('/api/members/byLeader', { 
      params: { leader }
    });
    if (response.code === '200') {
      editMemberList.value = response.data || [];
    } else {
      ElMessage.error('获取成员列表失败: ' + response.msg);
    }
  } catch (error) {
    ElMessage.error('获取成员列表失败');
    console.error('获取成员列表失败:', error);
  } finally {
    editMemberLoading.value = false;
  }
}

// 加载当前用户作为leader的小组成员
const loadMembersByLeader = async (leader) => {
  if (!leader) {
    createMemberList.value = [];
    return;
  }
  createMemberLoading.value = true;
  try {
    const response = await request.get('/api/members/byLeader', { 
      params: { leader }
    });
    if (response.code === '200') {
      // 后端已过滤掉leader自己
      createMemberList.value = response.data || [];
      // 不再自动设置小组成员，只加载列表供用户选择
      // createProjectForm.projectMembers = createMemberList.value.map(user => user.username);
    } else {
      ElMessage.error('获取成员列表失败: ' + response.msg);
    }
  } catch (error) {
    ElMessage.error('获取成员列表失败');
    console.error('获取成员列表失败:', error);
  } finally {
    createMemberLoading.value = false;
  }
}

// 加载项目列表数据
const loadProjects = async () => {
  loading.value = true;
  try {
    const user = getCurrentUserInfo();
    const response = await request.get('/api/kanban/projects', {
      params: {
        name: searchForm.name,
        status: searchForm.status,
        priority: searchForm.priority,
        username: user
      }
    });
    if (response.code === '200') {
      projectList.value = response.data || [];
      pagination.total = projectList.value.length;
    } else {
      ElMessage.error('获取项目列表失败: ' + response.msg);
    }
  } catch (error) {
    ElMessage.error('获取项目列表失败');
    console.error('获取项目列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(async () => {
  // 获取当前用户信息
  currentUser.value = getCurrentUserInfo();
  if (!currentUser.value) {
    // 如果获取不到当前用户信息，尝试重新获取
    setTimeout(() => {
      currentUser.value = getCurrentUserInfo();
      if (currentUser.value) {
        // 只设置项目负责人，不加载小组成员
        createProjectForm.projectLeader = currentUser.value;
      }
    }, 1000);
  } else {
    // 只设置项目负责人，不加载小组成员
    createProjectForm.projectLeader = currentUser.value;
  }
  
  await loadProjects();
  await loadLeaders();
})

// 重置新建项目表单
const resetCreateForm = () => {
  createProjectFormRef.value?.resetFields();
  createProjectForm.projectName = '';
  createProjectForm.projectDescription = '';
  createProjectForm.projectLeader = currentUser.value || '';
  createProjectForm.projectPriority = '中';
  createProjectForm.startTime = '';
  createProjectForm.endTime = '';
  // 清空小组成员列表
  createProjectForm.projectMembers = [];
  // 加载可选的小组成员列表，但不自动添加
  if (currentUser.value) {
    loadMembersByLeader(currentUser.value);
  } else {
    createMemberList.value = [];
  }
}

// 重置编辑项目表单
const resetEditForm = () => {
  // 使用nextTick确保DOM更新后再重置表单
  // 这可以避免在对话框关闭动画过程中出现DOM引用错误
  setTimeout(() => {
    if (editProjectFormRef.value) {
      editProjectFormRef.value.resetFields();
      editProjectForm.projectName = '';
      editProjectForm.projectDescription = '';
      editProjectForm.projectLeader = '';
      editProjectForm.projectPriority = '中';
      editProjectForm.startTime = '';
      editProjectForm.endTime = '';
      editProjectForm.projectMembers = [];
      editMemberList.value = [];
      currentProjectId.value = null;
    }
  }, 300); // 给予足够的时间让对话框关闭动画完成
}

// 搜索处理函数
const doSearch = () => {
  pagination.page = 1;
  loadProjects();
}

// 使用防抖包装的搜索处理函数
const handleSearch = debounce(doSearch, 500)

const handleSizeChange = () => {
  loadProjects();
}

const handleCurrentChange = () => {
  loadProjects();
}

const viewProject = (project) => {
  router.push(`/projects/${project.projectId}`);
}
// 编辑项目
const editProject = async (project) => {
  try {
    // 先清空表单数据，避免引用旧数据
    Object.assign(editProjectForm, {
      projectName: '',
      projectDescription: '',
      projectLeader: '',
      projectPriority: '中',
      startTime: '',
      endTime: '',
      projectMembers: []
    });
    
    // 设置当前项目ID
    currentProjectId.value = project.projectId;
    
    // 解析项目成员
    const membersArray = project.projectMembers ? project.projectMembers.split(',').filter(m => m) : [];

    // 确保项目负责人在成员列表中
    if (project.projectLeader && !membersArray.includes(project.projectLeader)) {
      membersArray.push(project.projectLeader);
    }

    // 加载负责人列表
    await loadLeaders();

    // 加载当前负责人的小组成员
    if (project.projectLeader) {
      await loadEditMembers(project.projectLeader);
    }
    
    // 复制项目数据到编辑表单
    Object.assign(editProjectForm, {
      projectName: project.projectName,
      projectDescription: project.projectDescription,
      projectLeader: project.projectLeader,
      projectPriority: project.projectPriority || '中',
      startTime: project.startTime ? new Date(project.startTime) : '',
      endTime: project.endTime ? new Date(project.endTime) : '',
      projectMembers: membersArray
    });

    // 显示编辑弹窗
    showEditDialog.value = true;
    
    // 确保表单验证状态重置
    setTimeout(() => {
      if (editProjectFormRef.value) {
        editProjectFormRef.value.clearValidate();
      }
    }, 100);
  } catch (error) {
    console.error('打开编辑对话框时出错:', error);
    ElMessage.error('打开编辑对话框时出错');
  }
}

// 安全关闭编辑对话框
const closeEditDialog = () => {
  // 先清空表单数据，避免在关闭动画过程中出现引用错误
  Object.assign(editProjectForm, {
    projectName: '',
    projectDescription: '',
    projectLeader: '',
    projectPriority: '中',
    startTime: '',
    endTime: '',
    projectMembers: []
  });
  // 关闭对话框
  showEditDialog.value = false;
};

// 处理编辑项目负责人变更
const handleEditLeaderChange = async (leader) => {
  // 清空当前成员选择
  editProjectForm.projectMembers = [];
  // 加载新负责人的小组成员
  await loadEditMembers(leader);
}

const manageMembers = (project) => {
  router.push(`/projects/${project.projectId}`);
}

const deleteProject = async (project) => {
  ElMessageBox.confirm('确定要删除此项目吗？删除后无法恢复！', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/kanban/projects/${project.projectId}`);
      if (response.code === '200') {
        ElMessage.success('项目已删除');
        loadProjects();
      } else {
        ElMessage.error('删除项目失败: ' + response.msg);
      }
    } catch (error) {
      ElMessage.error('删除项目失败');
      console.error('删除项目失败:', error);
    }
  });
}

// 保存新建项目
const saveCreateProject = async () => {
  try {
      await createProjectFormRef.value.validate();
      savingCreate.value = true;

      // 确保当前用户信息已加载
      if (!currentUser.value) {
        ElMessage.error('无法获取当前用户信息，请刷新页面重试');
        savingCreate.value = false;
        return;
      }
      
      // 转换成员数组为逗号分隔字符串
      let projectMembersArray = [...createProjectForm.projectMembers];
      // 确保项目负责人在成员列表中
      if (!projectMembersArray.includes(createProjectForm.projectLeader)) {
        projectMembersArray.push(createProjectForm.projectLeader);
      }
      const projectMembersStr = projectMembersArray.join(',');

      // 处理日期格式 - 确保使用正确的格式
      let startTimeFormatted = null;
      let endTimeFormatted = null;
      
      if (createProjectForm.startTime) {
        const startDate = createProjectForm.startTime instanceof Date ? 
          createProjectForm.startTime : new Date(createProjectForm.startTime);
        startTimeFormatted = startDate.toISOString();
      }
      
      if (createProjectForm.endTime) {
        const endDate = createProjectForm.endTime instanceof Date ? 
          createProjectForm.endTime : new Date(createProjectForm.endTime);
        endTimeFormatted = endDate.toISOString();
      }

      const formData = {
        ...createProjectForm,
        projectMembers: projectMembersStr,
        startTime: startTimeFormatted,
        endTime: endTimeFormatted
      };

      // 输出请求数据到控制台，用于调试
      console.log('发送创建项目请求:', {
        url: '/api/kanban/projects',
        data: formData
      });

      const response = await request.post('/api/kanban/projects', formData);

    if (response.code === '200') {
      ElMessage.success('项目创建成功');
      // 先重置状态，再关闭对话框，避免DOM引用错误
      savingCreate.value = false;
      // 先将表单数据清空，避免在关闭动画过程中出现引用错误
      Object.assign(createProjectForm, {
        projectName: '',
        projectDescription: '',
        projectLeader: currentUser.value,
        projectPriority: '中',
        startTime: '',
        endTime: '',
        projectMembers: []
      });
      // 关闭对话框
      showCreateDialog.value = false;
      // 重新加载项目列表
      loadProjects();
    } else {
      ElMessage.error('创建项目失败: ' + response.msg);
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      let errorMsg = '创建项目失败';
      if (error.response && error.response.data) {
        errorMsg += ': ' + (error.response.data.msg || JSON.stringify(error.response.data));
      } else if (error.message) {
        errorMsg += ': ' + error.message;
      }
      ElMessage.error(errorMsg);
      console.error('创建项目失败:', error);
    }
  } finally {
    savingCreate.value = false;
  }
}

// 保存编辑项目
const saveEditProject = async () => {
  try {
    await editProjectFormRef.value.validate();
    savingEdit.value = true;

    // 转换成员数组为逗号分隔字符串
    let projectMembersArray = [...editProjectForm.projectMembers];
    // 确保项目负责人在成员列表中
    if (!projectMembersArray.includes(editProjectForm.projectLeader)) {
      projectMembersArray.push(editProjectForm.projectLeader);
    }
    const projectMembersStr = projectMembersArray.join(',');

    // 处理日期格式 - 确保使用正确的格式
    let startTimeFormatted = null;
    let endTimeFormatted = null;
    
    if (editProjectForm.startTime) {
      const startDate = editProjectForm.startTime instanceof Date ? 
        editProjectForm.startTime : new Date(editProjectForm.startTime);
      startTimeFormatted = startDate.toISOString();
    }
    
    if (editProjectForm.endTime) {
      const endDate = editProjectForm.endTime instanceof Date ? 
        editProjectForm.endTime : new Date(editProjectForm.endTime);
      endTimeFormatted = endDate.toISOString();
    }

    const formData = {
      ...editProjectForm,
      projectMembers: projectMembersStr,
      startTime: startTimeFormatted,
      endTime: endTimeFormatted
    };

    // 输出请求数据到控制台，用于调试
    console.log('发送更新项目请求:', {
      url: `/api/kanban/projects/${currentProjectId.value}`,
      data: formData
    });

    const response = await request.put(`/api/kanban/projects/${currentProjectId.value}`, formData);

    console.log('更新项目响应:', response);

    if (response.code === '200') {
      ElMessage.success('项目更新成功');
      // 先重置状态，再关闭对话框，避免DOM引用错误
      savingEdit.value = false;
      // 先将表单数据清空，避免在关闭动画过程中出现引用错误
      Object.assign(editProjectForm, {
        projectName: '',
        projectDescription: '',
        projectLeader: '',
        projectPriority: '中',
        startTime: '',
        endTime: '',
        projectMembers: []
      });
      // 关闭对话框
      showEditDialog.value = false;
      // 重新加载项目列表
      loadProjects();
    } else {
      ElMessage.error('更新项目失败: ' + response.msg);
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      let errorMsg = '更新项目失败';
      if (error.response && error.response.data) {
        errorMsg += ': ' + (error.response.data.msg || JSON.stringify(error.response.data));
      } else if (error.message) {
        errorMsg += ': ' + error.message;
      }
      ElMessage.error(errorMsg);
      console.error('更新项目失败详情:', error);
      // 输出更多错误信息用于调试
      if (error.response) {
        console.error('错误响应状态:', error.response.status);
        console.error('错误响应数据:', error.response.data);
      }
    }
  } finally {
    savingEdit.value = false;
  }
}

// 状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case '进行中': return '#409EFF';
    case '已完成': return '#67C23A';
    case '已暂停': return '#E6A23C';
    case '已取消': return '#F56C6C';
    default: return '#C0C4CC';
  }
}

// 状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '进行中': return 'primary';
    case '已完成': return 'success';
    case '已暂停': return 'warning';
    case '已取消': return 'danger';
    default: return 'info';
  }
}

// 状态文本
const getStatusText = (status) => {
  return status || '未设置';
}

// 优先级标签类型
const getPriorityTagType = (priority) => {
  switch (priority) {
    case '高': return 'danger';
    case '中': return 'warning';
    case '低': return 'info';
    default: return 'default';
  }
}

// 优先级文本
const getPriorityText = (priority) => {
  return priority || '未设置';
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}
</script>

<style scoped>
.el-table {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-progress-bar__outer) {
  background-color: #e4e7ed;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f5f7fa;
}
</style>